package com.parlons.activities;

/**
 * This activity is the loading activity, which checks the internet connection and user authentication
 */

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.TextView;
import android.widget.Toast;

import com.parlons.DatabaseServices;
import com.parlons.R;
import com.parlons.SmackServices;

import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;

import java.util.List;


public class SplashActivity extends Activity {

    private static final int NOTLOGGEDIN = 0; // 连线,未登录
    private static final int LOGGEDIN = 1; // 连线,已登录
    private static final int OFFLINE = 2; // 离线
    private static final int SHOW_TIME_MIN = 800; // 最短的loading画面显示时间

    private TextView mVersionNameText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        AsyncTask<Void, Void, Integer> asyncTask = new AsyncTask<Void, Void, Integer>() {

            @Override
            protected Integer doInBackground(Void... params) {
                /**
                 * *  Check the internet connection and user authentication
                 * */
                int result;
                long startTime = System.currentTimeMillis();
                result = check();
                long loadingTime = System.currentTimeMillis() - startTime;
                if (loadingTime < SHOW_TIME_MIN) {
                    try {
                        Thread.sleep(SHOW_TIME_MIN - loadingTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                return result;
            }

            @Override
            protected void onPostExecute(Integer result) {
                switch (result) {
                    case NOTLOGGEDIN: {
                        Intent i = new Intent(SplashActivity.this, LogInActivity.class);
                        startActivity(i);
                        finish(); // close the activity
                        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                        break;
                    }
                    case LOGGEDIN: {
                        Intent i = new Intent(SplashActivity.this, MainActivity.class);
                        startActivity(i);
                        finish(); // close the activity
                        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                        break;
                    }
                    case OFFLINE: {
                        Toast toast = Toast.makeText(getApplicationContext(),
                                "无法连接到网络", Toast.LENGTH_LONG);
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        toast.show();
                        break;
                    }
                }

            }
        };
        asyncTask.execute(new Void[]{});
    }

    @Override
    protected void onResume() {
        super.onResume();
        setContentView(R.layout.activity_splash);

        AsyncTask<Void, Void, Integer> asyncTask = new AsyncTask<Void, Void, Integer>() {

            @Override
            protected Integer doInBackground(Void... params) {
                /**
                 * *  Check the internet connection and user authentication
                 * */
                int result;
                long startTime = System.currentTimeMillis();
                result = check();
                long loadingTime = System.currentTimeMillis() - startTime;
                if (loadingTime < SHOW_TIME_MIN) {
                    try {
                        Thread.sleep(SHOW_TIME_MIN - loadingTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                return result;
            }

            @Override
            protected void onPostExecute(Integer result) {
                switch (result) {
                    case NOTLOGGEDIN: {
                        Intent i = new Intent(SplashActivity.this, LogInActivity.class);
                        startActivity(i);
                        finish(); // close the activity
                        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                        break;
                    }
                    case LOGGEDIN: {
                        Intent i = new Intent(SplashActivity.this, MainActivity.class);
                        startActivity(i);
                        finish(); // close the activity
                        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                        break;
                    }
                    case OFFLINE: {
                        Toast toast = Toast.makeText(getApplicationContext(),
                                "无法连接到网络", Toast.LENGTH_LONG);
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        toast.show();
                        break;
                    }
                }

            }
        };
        asyncTask.execute(new Void[]{});
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        setContentView(R.layout.activity_splash);

        AsyncTask<Void, Void, Integer> asyncTask = new AsyncTask<Void, Void, Integer>() {

            @Override
            protected Integer doInBackground(Void... params) {
                /**
                 * *  Check the internet connection and user authentication
                 * */
                int result;
                long startTime = System.currentTimeMillis();
                result = check();
                long loadingTime = System.currentTimeMillis() - startTime;
                if (loadingTime < SHOW_TIME_MIN) {
                    try {
                        Thread.sleep(SHOW_TIME_MIN - loadingTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                return result;
            }

            @Override
            protected void onPostExecute(Integer result) {
                switch (result) {
                    case NOTLOGGEDIN: {
                        Intent i = new Intent(SplashActivity.this, LogInActivity.class);
                        startActivity(i);
                        finish(); // close the activity
                        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                        break;
                    }
                    case LOGGEDIN: {
                        Intent i = new Intent(SplashActivity.this, MainActivity.class);
                        startActivity(i);
                        finish(); // close the activity
                        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                        break;
                    }
                    case OFFLINE: {
                        Toast toast = Toast.makeText(getApplicationContext(),
                                "无法连接到网络", Toast.LENGTH_LONG);
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        toast.show();
                        break;
                    }
                }

            }
        };
        asyncTask.execute(new Void[]{});
    }

    private int check() {
        boolean connected = SmackServices.conServer(this);
        System.out.println(connected);
        if (!connected) {
            return OFFLINE;
        } else {
            SharedPreferences settings = getSharedPreferences("parlons", Activity.MODE_PRIVATE);
            String defaultUser = settings.getString("default_user", null);
            String password = settings.getString("password", null);
            if (defaultUser != null && password != null) {
                SmackServices.login(defaultUser, password);
            }
            if (SmackServices.getConnection().isAuthenticated()) {
                Roster roster = SmackServices.getConnection().getRoster();
                List<RosterEntry> friendList = SmackServices.getAllEntries(roster);
                DatabaseServices DBService = DatabaseServices.getInstance(getApplicationContext());
                for (RosterEntry friend : friendList) {
                    System.out.println("A friend");
                    String friendUsername = SmackServices.getUserNameFromJID(friend.getUser());
                    if (!DBService.friendExists(SmackServices.getUserName(), friendUsername)) {
                        DBService.addFriend(SmackServices.getUserName(), friendUsername, friend.getName());
                    }
                }
                DBService.close();
                return LOGGEDIN;
            } else {
                return NOTLOGGEDIN;
            }
        }
    }

}
